//
//  GoogleOpenTableViewController.m
//  bitcoin
//
//  Created by caiyajun on 2018/6/6.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "GoogleOpenTableViewController.h"
#import "GooglePasswordView.h"
@interface GoogleOpenTableViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *googleImage;
@property (weak, nonatomic) IBOutlet UILabel *gooleLabel;


@end

@implementation GoogleOpenTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.leftBarButtonItem = back;
    //每次请求新的key
    [self requstNewAddress];
    //    判断是否谷歌验证过
    
//    [LSRequestManager getRequestWithURL:HUOBI(@"api/user/userSecurityInfo")
//                                 params:nil
//                                success:^(NSDictionary *responseData) {
//                                    if ([responseData[@"ret"] integerValue ] == 0) {
//                                        NSString*google_key=[NSString stringWithFormat:@"%@",responseData[@"data"][@"google_key"]];
//
//                                        if ([google_key isEqualToString:@""]||[google_key isKindOfClass:[NSNull class]]) {
//                                            [self requstNewAddress];
//                                        }else{
//                                            [self useOldAddress];
//                                        }
//
//
//                                    } else {
//                                        [MBProgressHUD showError:responseData[@"msg"]];
//                                    }
//                                }
//                                failure:^(NSError *error) {
//
//                                }
//                                showHUD:NO];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

}
-(void)useOldAddress{
    [LSRequestManager postRequestWithURL:GOOGLE(@"service-business-googleauth/v0.1.0/getQrCode")
                                  params:nil
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         NSString*address=[NSString stringWithFormat:@"%@",responseData[@"data"]];
                                         
                                         CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
                                         [filter setDefaults];
                                         NSData *data  = [address dataUsingEncoding:NSUTF8StringEncoding];
                                         [filter setValue:data forKey:@"inputMessage"];
                                         CIImage *outputImage = [filter outputImage];
                                         self.googleImage.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
                                         
                                         if ([address rangeOfString:@"="].location == NSNotFound) {
                                             NSLog(@"string 不存在 =");
                                             self.gooleLabel.text=@"";
                                         } else {
                                             NSLog(@"string 包含 =");
                                             NSArray *array = [address componentsSeparatedByString:@"="];
                                             self.gooleLabel.text=array.lastObject;
                                         }
                                         
                                         
                                     } else {
                                         self.googleImage.image=nil;
                                         self.gooleLabel.text=@"";
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     self.googleImage.image=nil;
                                     self.gooleLabel.text=@"";
                                     
                                 }
                                 showHUD:NO];
}
-(void)requstNewAddress{
    [LSRequestManager postRequestWithURL:GOOGLE(@"service-business-googleauth/v0.1.0/genAuth")
                                  params:nil
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         NSString*address=[NSString stringWithFormat:@"%@",responseData[@"data"]];
                                         
                                         CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
                                         [filter setDefaults];
                                         NSData *data  = [address dataUsingEncoding:NSUTF8StringEncoding];
                                         [filter setValue:data forKey:@"inputMessage"];
                                         CIImage *outputImage = [filter outputImage];
                                         self.googleImage.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200];
                                         
                                         if ([address rangeOfString:@"="].location == NSNotFound) {
                                             NSLog(@"string 不存在 =");
                                             self.gooleLabel.text=@"";
                                         } else {
                                             NSLog(@"string 包含 =");
                                             NSArray *array = [address componentsSeparatedByString:@"="];
                                             self.gooleLabel.text=array.lastObject;
                                         }
                                         
                                         
                                     } else {
                                         self.googleImage.image=nil;
                                         self.gooleLabel.text=@"";
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     self.googleImage.image=nil;
                                     self.gooleLabel.text=@"";
                                     
                                 }
                                 showHUD:NO];
}
- (void)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    //设置比例
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap（位图）;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 0;
}
- (IBAction)copyAction {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.gooleLabel.text;
    [MBProgressHUD showSuccess:@"已复制到剪贴板"];
    
    
    
}

- (IBAction)nextAction {
    

    
    
    
    
    GooglePasswordView *googlePasswordView = [GooglePasswordView xib];
    [[UIApplication sharedApplication].keyWindow addSubview:googlePasswordView];
    __weak typeof(googlePasswordView) weakGooglePasswordView = googlePasswordView;
    googlePasswordView.submitActionBlock = ^(NSString *str) {
        NSLog(@"passwordstr------%@",str);

        NSDictionary *param = @{@"code" : str};
        [weakGooglePasswordView removeFromSuperview];
        NSLog(@"%@",GOOGLE(@"service-business-googleauth/v0.1.0/verifyCode"));
        [LSRequestManager postRequestWithURL:GOOGLE(@"service-business-googleauth/v0.1.0/verifyCode")
                                     params:param
                                    success:^(NSDictionary *responseData) {
                                        if ([responseData[@"ret"] integerValue ] == 0) {
                                            [MBProgressHUD showError:responseData[@"msg"]];
                                            [self setGoogleStatus];

                                        } else {


                                            [MBProgressHUD showError:responseData[@"msg"]];
                                        }
                                    }
                                    failure:^(NSError *error) {

                                    }
                                    showHUD:NO];




    };
    
}

-(void)setGoogleStatus{
    NSDictionary *param= @{@"type" : @"3",
                           @"on" : @"1"};
    [LSRequestManager putRequestWithURL:HUOBI(@"api/user/setSecrityMethod")
                                 params:param
                                success:^(NSDictionary *responseData) {
                                    if ([responseData[@"ret"] integerValue ] == 0) {
                                        [UserDefaults setObject:@"1" forKey:K_ISGOOGLE];
                                        [UserDefaults synchronize];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"openGoogleSafeNoti" object:nil];
                                        
                                        
                                        [self.navigationController popViewControllerAnimated:YES];
                                        
                                        
                                        
                                        
                                        
                                        
                                        
                                    } else {
                                        [MBProgressHUD showError:responseData[@"msg"]];
                                    }
                                }
                                failure:^(NSError *error) {
                                    
                                }
                                showHUD:NO];
}
@end
